﻿using SLClient.CustomerControls;
using SLClient.Extension;
using SLClient.Infrastructure;
using SLClient.ServiceAPI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;

namespace SLClient.ViewModels
{
    public class LowerManagerViewModel : ViewModelBase
    {
        private ObservableCollection<UserInfo> _lowerList = new ObservableCollection<UserInfo>();
        private Visibility _processVisibity = 0;
        private SearchUserWindow _searchUserWindow;
        private UserInfo _selectedUserInfo;

        public LowerManagerViewModel()
        {
            this.PageCollection = new PagedCollectionView(this._lowerList);
            this.CommandInit();
            this.GetCurrentLower(ViewDispatcher.LoginUser.UserId);
        }

        public void AddLower()
        {
            UserInfo info2 = new UserInfo {
                UserAccount = string.Empty,
                UserNickName = string.Empty,
                UserPwd = string.Empty
            };
            UserInfo newUserInfo = info2;
            newUserInfo.ParentId = new Guid?(ViewDispatcher.LoginUser.UserId);
            LowerInfoWindow window2 = new LowerInfoWindow(this._lowerList, newUserInfo, "add") {
                Title = "添加下级"
            };
            window2.Show();
        }

        private void CommandInit()
        {
            RelayCommand command = new RelayCommand(AddLower) {
                IsEnabled = true
            };
            this.AddCommand = command;
        }

        public void EditLower()
        {
            LowerInfoWindow window2 = new LowerInfoWindow(this._lowerList, this._selectedUserInfo, "edit") {
                Title = "修改下级"
            };
            window2.Show();
        }

        public void GetChildLowerList(Guid navguid, ref int postion, ref List<NavUserInfo> list)
        {
            Func<NavUserInfo, bool> func = null;
            if (navguid != Guid.Empty)
            {
                this.GetCurrentLower(navguid);
                postion = 0;
                if (navguid == ViewDispatcher.LoginUser.UserId)
                {
                    list = new List<NavUserInfo>();
                }
                else
                {
                    if (func == null)
                    {
                        func = (s) =>
                        {
                            return s.UserId == navguid;
                        };
                    }
                    NavUserInfo item = Enumerable.First<NavUserInfo>(list, func);
                    int index = list.IndexOf(item);
                    int count = list.Count;
                    list.RemoveRange(index + 1, count - 1);
                }
            }
            else
            {
                int? userType = null ;
                if (this._selectedUserInfo.UserId != Guid.Empty)
                {
                    userType = this._selectedUserInfo.UserType;
                }
                if (((userType.GetValueOrDefault() == 0) && userType.HasValue) && (this._selectedUserInfo.Tag != 1))
                {
                    this.GetCurrentLower(this._selectedUserInfo.UserId);
                    postion = 0;
                    NavUserInfo info2 = new NavUserInfo {
                        UserId = this._selectedUserInfo.UserId,
                        UserName = this._selectedUserInfo.UserAccount
                    };
                    list.Add(info2);
                }
            }
        }

        public void GetCurrentLower(Guid userId)
        {
            ServiceClient instance = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
            instance.GetAgentsByUserIdCompleted += 
                delegate (object obj, GetAgentsByUserIdCompletedEventArgs arg) {                
                this.LowerList.Clear();
                foreach (UserInfo info in arg.Result)
                {
                    this.LowerList.Add(info);
                }
                Guid currentParentGuid = new Guid(arg.UserState.ToString());
                Enumerable.FirstOrDefault<UserInfo>(this.LowerList, 
                    new Func<UserInfo, bool>((s) => { return s.UserId == currentParentGuid; })).Tag = 1;
                this.ProcessVisibity = Visibility.Collapsed;
            };
            instance.GetAgentsByUserIdAsync(userId, userId);
        }

        public void RefreshList(ref int pos)
        {
            this.ProcessVisibity = 0;
            this.GetCurrentLower(ViewDispatcher.LoginUser.UserId);
            pos = 0;
        }

        private void Search()
        {
            PagedCollectionView pageCollection = this.PageCollection;
            pageCollection.Filter = (Predicate<object>)Delegate.Combine(pageCollection.Filter, 
               new Func<UserInfo, bool>((s) => { return s.UserAccount.Contains(this._searchUserWindow.tbUserName.Text);}));
        }

        public void SearchList(ref int pos)
        {
            this._searchUserWindow = new SearchUserWindow();
            pos = 0;
            this._searchUserWindow.SearchHander += new EventHandler(this.SearchUserWindowSearchHandler);
            this._searchUserWindow.Show();
        }

        private void SearchUserWindowSearchHandler(object sender, EventArgs e)
        {
            this.Search();
        }

        public ICommand AddCommand { get; set; }

        public ObservableCollection<UserInfo> LowerList
        {
            get
            {
                return this._lowerList;
            }
            set
            {
                this._lowerList = value;
            }
        }

        public ICommand MouseUpCommand { get; set; }

        public PagedCollectionView PageCollection { get; set; }

        public Visibility ProcessVisibity
        {
            get
            {
                return this._processVisibity;
            }
            set
            {
                this._processVisibity = value;
                base.Notify<Visibility>(() => this.ProcessVisibity);
            }
        }

        public ICommand RefreshListCommand { get; set; }

        public ICommand SearchListCommand { get; set; }

        public UserInfo SelectedUserInfo
        {
            get
            {
                return this._selectedUserInfo;
            }
            set
            {
                this._selectedUserInfo = value;
                base.Notify<UserInfo>(() => this.SelectedUserInfo);
            }
        }

        public ICommand TransitionCommand { get; set; }
    }

}

